﻿using Liju.Common;
using LiJu.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using Liju.Model;

namespace LiJu
{
    public partial class Setting : Form
    {
        SettingOldValue settingOldValue = new SettingOldValue();
        
        List<ScrewModel> screwList;
        public Setting()
        {
            InitializeComponent();
            
            // 加载时启用默认双缓冲并提供无闪烁的图形呈现：
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲

            //加载本地串口
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                CbxComOne.Items.Add(port);
                //CbxComThree.Items.Add(port);
            }
        }

        /// <summary>
        /// 防止闪屏
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }


        private void Setting_Load(object sender, EventArgs e)
        {
            //页面加载时控制启用功能
            SystemMenuIsFunction();
            //asc.controllInitializeSize(this);

            DataTable dt = BLL.Bll.GetSettingData();
            if (dt.Rows.Count > 0)
            {

                settingOldValue.OldValue1 = dt.Rows[0]["SaveRecordDay"].ToString();
                settingOldValue.OldValue2 = dt.Rows[0]["CoordinateDeviation"].ToString();
                settingOldValue.OldValue5 = dt.Rows[0]["CoordinateDeviationZ"].ToString();

                TbxId.Text = dt.Rows[0]["Id"].ToString();
                TbxDay.Text = settingOldValue.OldValue1;
                TbxDeviation.Text = settingOldValue.OldValue2;
                TbxDeviationZ.Text = settingOldValue.OldValue5;
                TbxDianPiSpeedMax.Text = dt.Rows[0]["DianPiSpeedMax"].ToString();
                numWeiYIChaoXianTime.Text = dt.Rows[0]["WeiYIChaoXianTime"].ToString().Trim();

                numGongXuNo.Text = dt.Rows[0]["GongXuNo"].ToString().Trim();
                cbNGIsFinisth.Text = Convert.ToBoolean(dt.Rows[0]["NGIsFinisth"]) ? "作业结束" : "工艺二次判定";
                cbOKDianPiEnable.Text = Convert.ToBoolean(dt.Rows[0]["OKDianPiEnable"]) ? "禁用" : "不禁用";
                tbMesIP.Text = dt.Rows[0]["MesIP"].ToString().Trim();
                tbMesPort.Text = dt.Rows[0]["MesPort"].ToString().Trim();
                tbLine.Text = dt.Rows[0]["MesLine"].ToString().Trim();
                tbWorkStation.Text = dt.Rows[0]["MesWorkStation"].ToString().Trim();
                tbZiYuanNo.Text = dt.Rows[0]["MesZiYuanNo"].ToString().Trim();
                cbLedState.Checked = dt.Rows[0]["LedEnable"].ToString() == "1" ? true : false;
                numTuiGanRunTime.Text = dt.Rows[0]["TuiGanRunTime"].ToString().Trim();                

                cbState0.Checked = false;
                cbState1.Checked = false;
                cbState2.Checked = false;
                cbState3.Checked = false;
                string[] TaoTongStateList = dt.Rows[0]["TaoTongStateList"].ToString().Trim().Split(',');
                if (TaoTongStateList.Length > 0 && TaoTongStateList[0] == "1")
                {
                    cbState0.Checked = true;
                }
                if (TaoTongStateList.Length > 1 && TaoTongStateList[1] == "1")
                {
                    cbState1.Checked = true;
                }
                if (TaoTongStateList.Length > 2 && TaoTongStateList[2] == "1")
                {
                    cbState2.Checked = true;
                }
                if (TaoTongStateList.Length > 3 && TaoTongStateList[3] == "1")
                {
                    cbState3.Checked = true;
                }
                cbSwitchBatch.Checked = ConfigurationManager.AppSettings["EnableBatchQuickSwitch"] == "1" ? true : false;//是否启用批头快速切换
            }

            //获取列表数据
            GetDeviceData();

            //须从UI线程另启动一个线程,在新线程调用异步刷新提示信息
            Thread threadIO = new Thread(new ThreadStart(IOMonitor));
            threadIO.IsBackground = true;
            threadIO.Start();
        }
        
        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl.TabPages.Count > 0)
            {
                // 判断当前切换的tab,调用对应的加载方案
                switch (tabControl.SelectedTab.Name)
                {
                    case "tabLsSet":
                        LoadScrewModelInfo();//加载螺丝仓数据
                        break;
                    case "tabLsOpLog":
                        LoadScrewLogInfo();//加载螺丝开关日志
                        break;
                        //case "tabMenu":
                        //    LoadSystemMenuInfo();
                        //    break;
                }
            }
        }

        private void SaveData_Click(object sender, EventArgs e)
        {
            //记录天数 /坐标
            string SaveRecordDay = TbxDay.Text;
            string CoordinateDeviation = TbxDeviation.Text;
            string CoordinateDeviationZ = TbxDeviationZ.Text;
            int DianPiSpeedMax = Convert.ToInt32(TbxDianPiSpeedMax.Text);
            int did = Convert.ToInt32(TbxId.Text);

            bool bOKDianPiEnable = cbOKDianPiEnable.Text == "禁用" ? true : false;
            bool bNGIsFinisth = cbNGIsFinisth.Text == "作业结束" ? true : false;

            int[] arrTaoTongState = { 0, 0, 0, 0 };
            if (cbState0.Checked)
            {
                arrTaoTongState[0] = 1;
            }
            if (cbState1.Checked)
            {
                arrTaoTongState[1] = 1;
            }
            if (cbState2.Checked)
            {
                arrTaoTongState[2] = 1;
            }
            if (cbState3.Checked)
            {
                arrTaoTongState[3] = 1;
            }
            int nLedEnable = 0;
            if (cbLedState.Checked)
            {
                nLedEnable = 1;
            }
            // 写入配置
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["EnableBatchQuickSwitch"].Value = cbSwitchBatch.Checked ? "1" : "0";
            config.Save(ConfigurationSaveMode.Modified);
            // 强制刷新配置
            ConfigurationManager.RefreshSection("appSettings");

            if (string.IsNullOrWhiteSpace(SaveRecordDay) || string.IsNullOrWhiteSpace(CoordinateDeviation) ||
                string.IsNullOrWhiteSpace(cbOKDianPiEnable.Text)|| string.IsNullOrWhiteSpace(cbNGIsFinisth.Text))
            {
                MessageBox.Show("记录保存天数、坐标偏差、Pass后禁用电批使能 不能为空！", "参数异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                try
                {
                    string[] arrString = tbWorkStation.Text.Split('-');
                    if (arrString.Length < 3 || (arrString.Length == 3 && string.IsNullOrWhiteSpace(arrString[2])))
                    {
                        MessageBox.Show("工站信息格式错误，请输入正确的工站信息。", "系统提示", MessageBoxButtons.OK);
                        return;
                    }
                    //保存顶部 天数和偏移位置
                    BLL.Bll.InsertAndUpdateSettingData(did, SaveRecordDay, CoordinateDeviation, CoordinateDeviationZ, 
                        DianPiSpeedMax, bOKDianPiEnable, bNGIsFinisth, (int)numGongXuNo.Value, string.Join(",", arrTaoTongState),
                        (int)numTuiGanRunTime.Value, nLedEnable,tbMesIP.Text.Trim(), tbMesPort.Text.Trim(), tbLine.Text.Trim(),
                        tbWorkStation.Text.Trim(), tbZiYuanNo.Text.Trim(), (int)numWeiYIChaoXianTime.Value);

                    for (int i = 0; i < 4; i++)
                    {
                        switch (i)
                        {
                            case 1:
                                int ComPortID1 = Convert.ToInt32(this.LblIdOne.Text); //ID
                                //string AppName1 = Convert.ToString(this.TbxNameOne.Text);//设备名称
                                string PortName1 = Convert.ToString(this.CbxComOne.Text); //COM /IP
                                //int BaudRate1 = Convert.ToInt32(this.CbxBrOne.Text);//波特率 /端口
                                //更新数据
                                BLL.Bll.UpdateComPortDaTa(ComPortID1, PortName1);
                                break;
                            case 2:
                                int ComPortID2 = Convert.ToInt32(this.lbID2.Text); //ID
                                //string AppName2 = Convert.ToString(this.tbName2.Text);//设备名称
                                string PortName2 = Convert.ToString(this.tbIp2.Text); //COM /IP
                                //int BaudRate2 = Convert.ToInt32(this.tbPort2.Text);//波特率 /端口
                                //更新数据
                                BLL.Bll.UpdateComPortDaTa(ComPortID2, PortName2);
                                break;
                            //case 3:
                            //    int ComPortID3 = Convert.ToInt32(this.LblIdThree.Text); //ID
                            //    //string AppName3 = Convert.ToString(this.TbxNameThree.Text);//设备名称
                            //    string PortName3 = Convert.ToString(this.CbxComThree.Text); //COM /IP
                            //    //int BaudRate3 = Convert.ToInt32(this.CbxBrThree.Text);//波特率 /端口
                            //    //更新数据
                            //    BLL.Bll.UpdateComPortDaTa(ComPortID3, PortName3);
                            //    break;
                            case 4:
                                int ComPortID4 = Convert.ToInt32(this.LblIdFour.Text); //ID
                                //string AppName4 = Convert.ToString(this.TbxNameFour.Text);//设备名称
                                string PortName4 = Convert.ToString(this.TbxIpOne.Text); //COM /IP
                                //int BaudRate4 = Convert.ToInt32(this.TbxPortOne.Text);//波特率 /端口
                                //更新数据
                                BLL.Bll.UpdateComPortDaTa(ComPortID4, PortName4);
                                break;
                        }
                    }

                    if (tabControl.TabPages.Count > 0)
                    {
                        // 判断当前切换的tab,调用对应的加载方案
                        switch (tabControl.SelectedTab.Name)
                        {
                            case "tabLsSet":
                                SeveMesCcrewmodelData();
                                break;
                                //case "tabRole":
                                //    LoadRoleManagerInfo();
                                //    break;
                                //case "tabMenu":
                                //    LoadSystemMenuInfo();
                                //    break;
                        }
                    }
                    MessageBox.Show("参数保存成功！");
                    return;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        private void Cancelbutton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 获取comPort表的所有数据，加载到datagridview中
        /// </summary>
        public void GetDeviceData()
        {
            DataTable comList = BLL.Bll.GetTCPData();
            if (comList.Rows.Count > 0)
            {
                for (int i = 0; i < comList.Rows.Count; i++)
                {
                    string ComPortID = Convert.ToString(comList.Rows[i]["ComPortID"]);
                    string AppName = Convert.ToString(comList.Rows[i]["AppName"]);
                    string PortName = Convert.ToString(comList.Rows[i]["PortName"]);
                    string BaudRate = Convert.ToString(comList.Rows[i]["BaudRate"]);
                    switch (AppName)
                    {
                        case "位移编码器":
                            this.LblIdOne.Text = ComPortID;
                            //this.TbxNameOne.Text = AppName;
                            this.CbxComOne.Text = PortName;
                            //this.CbxBrOne.Text = BaudRate;
                            break;
                        case "IO控制器":
                            this.lbID2.Text = ComPortID;
                            //this.tbName2.Text = AppName;
                            this.tbIp2.Text = PortName;
                            this.tbPort2.Text = BaudRate;
                            break;
                        //case "锁控制器":
                        //    this.LblIdThree.Text = ComPortID;
                        //    //this.TbxNameThree.Text = AppName;
                        //    this.CbxComThree.Text = PortName;
                        //    //this.CbxBrThree.Text = BaudRate;
                        //    break;
                        case "电批":
                            this.LblIdFour.Text = ComPortID;
                            //this.TbxNameFour.Text = AppName;
                            this.TbxIpOne.Text = PortName;
                            this.TbxPortOne.Text = BaudRate;
                            settingOldValue.OldValue3 = PortName;
                            settingOldValue.OldValue4 = BaudRate;
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// 页面功能加载
        /// </summary>
        public void SystemMenuIsFunction()
        {
            string userID = ConfigurationManager.AppSettings["UserID"];

            SaveData.Enabled = false;
            Cancelbutton.Enabled = false;
            
            //获取当前页面功能
            var menuRole = PageDataDto.SystemMenuRoleInfo();

            if (menuRole.Set_Cancel || userID == "admin")
            {
                Cancelbutton.Enabled = true;
            }
            if (menuRole.Set_Save || userID == "admin")
            {
                SaveData.Enabled = true;
            }
        }

        private void TbxDay_Leave(object sender, EventArgs e)
        {
            //匹配天数，最多365天，最小1天
            string pattern = @"^(1[0-9]{2}|[1-9][0-9]?|36[0-5]|[1-9])$";

            TextBoxIsMatchData(pattern, TbxDay, "输入的内容不符合规则，请重新输入！最小1天，最大365天", settingOldValue.OldValue1);
        }

        private void TbxDeviation_Leave(object sender, EventArgs e)
        {
            //匹配百分比，最多100，最小0.01
            string pattern = @"^(0(\.[0-9]{1,2})?|[1-9][0-9]?(\.[0-9]{1,2})?|100(\.00)?)$";

            TextBoxIsMatchData(pattern, TbxDeviation, "输入的内容不符合规则，请重新输入！最小为0.01，最大100", settingOldValue.OldValue2);
        }

        private void TbxDeviationZ_Leave(object sender, EventArgs e)
        {
            //匹配百分比，最多100，最小0.01
            string pattern = @"^(0(\.[0-9]{1,2})?|[1-9][0-9]?(\.[0-9]{1,2})?|100(\.00)?)$";

            TextBoxIsMatchData(pattern, TbxDeviationZ, "输入的内容不符合规则，请重新输入！最小为0.01，最大100", settingOldValue.OldValue5);
        }

        private void TbxIpOne_Leave(object sender, EventArgs e)
        {
            //IP地址规则
            string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

            TextBoxIsMatchData(pattern, TbxIpOne, "输入的内容不符合规则，请重新输入！", settingOldValue.OldValue3);
        }

        private void TbxPortOne_Leave(object sender, EventArgs e)
        {
            //端口规则
            string pattern = @"^(?:0|[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$";

            TextBoxIsMatchData(pattern, TbxPortOne, "输入的内容不符合规则，请重新输入！端口号应为0-65535 之间", settingOldValue.OldValue4);
        }

        /// <summary>
        /// 校验输入的内容是否符合规则
        /// </summary>
        /// <param name="pattern">正则表达式</param>
        /// <param name="textBox">文本框</param>
        /// <param name="errMsg">消息提示</param>
        public void TextBoxIsMatchData(string pattern, TextBox textBox, string errMsg, string oldValue = "")
        {
            //获取单元格的输入值
            string inputValue = textBox.Text;

            // 创建Regex对象并进行匹配测试
            Regex regex = new Regex(pattern);
            if (!regex.IsMatch(inputValue))
            {
                MessageBox.Show(errMsg, "异常提示！");

                // 设置焦点
                textBox.Text = oldValue;
                textBox.Focus();
                return;
            }
        }

        /// <summary>
        /// IO控制器 16IN值
        /// </summary>
        //bool[] arrayInValue;

        private void IOMonitor()
        {
            while (true)
            {
                if (UnifiedObj.DeviceConState[2] == 0)
                {
                    return;
                }
                if (UnifiedObj.GetTaoTongState(1))//套筒1灯
                {
                    lbState1.BackColor = System.Drawing.Color.Lime;
                }
                else
                {
                    lbState1.BackColor = System.Drawing.Color.Red;
                }
                if (UnifiedObj.GetTaoTongState(2))//套筒2灯
                {
                    lbState2.BackColor = System.Drawing.Color.Lime;
                }
                else
                {
                    lbState2.BackColor = System.Drawing.Color.Red;
                }
                if (UnifiedObj.GetTaoTongState(3))//套筒3灯
                {
                    lbState3.BackColor = System.Drawing.Color.Lime;
                }
                else
                {
                    lbState3.BackColor = System.Drawing.Color.Red;
                }
                if (UnifiedObj.GetTaoTongState(4))//套筒4灯
                {
                    lbState4.BackColor = System.Drawing.Color.Lime;
                }
                else
                {
                    lbState4.BackColor = System.Drawing.Color.Red;
                }
                Thread.Sleep(50);
            }
        }

        // 套筒IO 1234开
        private void BtOpen_Click(object sender, EventArgs e)
        {
            UnifiedObj.SetTaoTongOpen(true, Convert.ToInt16(((Button)sender).Name.Replace("btOpen", "")));
        }

        // 套筒IO 1234 关
        private void BtClose_Click(object sender, EventArgs e)
        {
            UnifiedObj.SetTaoTongOpen(false, Convert.ToInt16(((Button)sender).Name.Replace("btClose", "")));
        }

        /// <summary>
        /// 保存螺丝仓数据
        /// </summary>
        public void SeveMesCcrewmodelData()
        {
            try
            {
                for (int i = 0; i < DgvScrew.RowCount; i++)
                {
                    int Id = Convert.ToInt32(DgvScrew.Rows[i].Cells["Id"].Value);
                    string Model = Convert.ToString(DgvScrew.Rows[i].Cells["Model"].Value);
                    double ScrewLength = Convert.ToDouble(DgvScrew.Rows[i].Cells["ScrewLength"].Value);
                    string WuLiaoCode = Convert.ToString(DgvScrew.Rows[i].Cells["WuLiaoCode"].Value);
                    int Capacity = Convert.ToInt32(DgvScrew.Rows[i].Cells["Capacity"].Value);
                    int CapacityNow = Convert.ToInt32(DgvScrew.Rows[i].Cells["CapacityNow"].Value);
                    int CapacityNGNum = Convert.ToInt32(DgvScrew.Rows[i].Cells["CapacityNGNum"].Value);
                    int CapacityWarnNum = Convert.ToInt32(DgvScrew.Rows[i].Cells["CapacityWarnNum"].Value);
                    string MAC = Convert.ToString(DgvScrew.Rows[i].Cells["MAC"].Value);

                    string sql = $@"update screwmodel set Model='{Model}',ScrewLength={ScrewLength},WuLiaoCode='{WuLiaoCode}',
                                        Capacity={Capacity},CapacityNow={CapacityNow},CapacityNGNum={CapacityNGNum},
                                        CapacityWarnNum={CapacityWarnNum},MAC='{MAC}' where Id={Id}";

                    var result = Db.DalMySQL.ExecuteNonQuery(sql);
                }

                for (int i = 0; i < DgvScrewTwo.RowCount; i++)
                {
                    int Id = Convert.ToInt32(DgvScrewTwo.Rows[i].Cells["TwoId"].Value);
                    int Capacity = Convert.ToInt32(DgvScrewTwo.Rows[i].Cells["TwoCapacity"].Value);
                    int CapacityNow = Convert.ToInt32(DgvScrewTwo.Rows[i].Cells["TwoCapacityNow"].Value);
                    int CapacityNGNum = Convert.ToInt32(DgvScrewTwo.Rows[i].Cells["TwoCapacityNGNum"].Value);
                    int CapacityWarnNum = Convert.ToInt32(DgvScrewTwo.Rows[i].Cells["TwoCapacityWarnNum"].Value);
                    string MAC = Convert.ToString(DgvScrewTwo.Rows[i].Cells["TwoMAC"].Value);

                    string sql = $@"update screwmodel set Capacity={Capacity},CapacityNow={CapacityNow},CapacityNGNum={CapacityNGNum},
                            CapacityWarnNum={CapacityWarnNum},MAC='{MAC}'  where Id={Id}";

                    var result = Db.DalMySQL.ExecuteNonQuery(sql);
                }

                //修改成功。
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存异常！详情：" + ex.Message, "系统提示！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        /// <summary>
        /// 加载设备管理页面
        /// </summary>
        public void LoadScrewModelInfo()
        {
            DgvScrew.Rows.Clear();
            DgvScrewTwo.Rows.Clear();
            
            string sql = " SELECT * FROM screwmodel";

            //把datatable转换为ListClass
            screwList = UserOpMysql.ExecuteDataTable(sql).ConvertToListClass<ScrewModel>();
            
            foreach (var item in screwList)
            {
                if (item.Remark == "螺丝仓1" || item.Remark == "螺丝仓2")
                {
                    int index = DgvScrew.Rows.Add();
                    DgvScrew.Rows[index].Cells["Id"].Value = item.Id;
                    DgvScrew.Rows[index].Cells["Remark"].Value = item.Remark;
                    DgvScrew.Rows[index].Cells["Model"].Value = item.Model;
                    DgvScrew.Rows[index].Cells["ScrewLength"].Value = item.ScrewLength;
                    DgvScrew.Rows[index].Cells["WuLiaoCode"].Value = item.WuLiaoCode;
                    DgvScrew.Rows[index].Cells["Capacity"].Value = item.Capacity;
                    DgvScrew.Rows[index].Cells["CapacityNow"].Value = item.CapacityNow;
                    DgvScrew.Rows[index].Cells["CapacityNGNum"].Value = item.CapacityNGNum;
                    DgvScrew.Rows[index].Cells["CapacityWarnNum"].Value = item.CapacityWarnNum;
                    DgvScrew.Rows[index].Cells["MAC"].Value = item.MAC;
                }
                else if (item.Remark == "废螺丝仓")
                {
                    int index = DgvScrewTwo.Rows.Add();
                    DgvScrewTwo.Rows[index].Cells["TwoId"].Value = item.Id;
                    DgvScrewTwo.Rows[index].Cells["TwoRemark"].Value = item.Remark;
                    DgvScrewTwo.Rows[index].Cells["TwoCapacity"].Value = item.Capacity;
                    DgvScrewTwo.Rows[index].Cells["TwoCapacityNow"].Value = item.CapacityNow;
                    DgvScrewTwo.Rows[index].Cells["TwoCapacityNGNum"].Value = item.CapacityNGNum;
                    DgvScrewTwo.Rows[index].Cells["TwoCapacityWarnNum"].Value = item.CapacityWarnNum;
                    DgvScrewTwo.Rows[index].Cells["TwoMAC"].Value = item.MAC;
                }
            }
        }

        /// <summary>
        /// 加载锁开关记录
        /// </summary>
        public void LoadScrewLogInfo()
        {
            DgvScrewLog.Rows.Clear();

            //最近一个月的数据
            string sql = @"SELECT * FROM screwlog
                            WHERE CreateTime >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
                            ORDER BY CreateTime DESC; ";

            var screwList = UserOpMysql.ExecuteDataTable(sql);
            if (screwList.Rows.Count > 0)
            {
                for (int i = 0; i < screwList.Rows.Count; i++)
                {
                    int ChangeType = Convert.ToInt32(screwList.Rows[i]["ChangeType"]);

                    DgvScrewLog.Rows.Add();
                    DgvScrewLog.Rows[i].Cells[0].Value = screwList.Rows[i]["ScrewLogID"];
                    DgvScrewLog.Rows[i].Cells[1].Value = screwList.Rows[i]["ScrewID"];
                    DgvScrewLog.Rows[i].Cells[2].Value = screwList.Rows[i]["LockIO"];
                    DgvScrewLog.Rows[i].Cells[3].Value = ChangeType == 1 ? "加料" : "取料";
                    DgvScrewLog.Rows[i].Cells[4].Value = screwList.Rows[i]["ChangeNum"];
                    DgvScrewLog.Rows[i].Cells[5].Value = screwList.Rows[i]["ChangePreNum"];
                    DgvScrewLog.Rows[i].Cells[6].Value = screwList.Rows[i]["ChangeLastNum"];
                    DgvScrewLog.Rows[i].Cells[7].Value = screwList.Rows[i]["CreateTime"];

                    //DgvScrewLog.Rows[i].DefaultCellStyle.BackColor = ChangeType == 1 ? Color.Black : Color.RoyalBlue;
                }
            }
        }

        private void DgvScrew_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //结束编辑状态时校验输入内容是否符合规则
            CheckDataGridViewColumnValue((DataGridView)sender, e.RowIndex, e.ColumnIndex);
        }

        private void DgvScrewTwo_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //结束编辑状态时校验输入内容是否符合规则
            CheckDataGridViewColumnValue((DataGridView)sender, e.RowIndex, e.ColumnIndex);
        }

        /// <summary>
        /// 校验DataGridView 中列修改的参数是否符合规则
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <param name="RowIndex">行</param>
        /// <param name="ColumnIndex">列</param>
        public void CheckDataGridViewColumnValue(DataGridView dgv, int RowIndex, int ColumnIndex)
        {
            DataGridViewRow row = dgv.Rows[RowIndex];

            DataGridViewCell gridCell = row.Cells[ColumnIndex];

            string gridName = gridCell.OwningColumn.Name;

            //库存容量
            if (gridName == "Capacity" || gridName == "CapacityNow" || gridName == "CapacityNGNum" || gridName == "CapacityWarnNum")
            {

                string pattern = @"^[0-9]{1,10}$";

                // 创建Regex对象并进行匹配测试
                Regex regex = new Regex(pattern);
                if (!regex.IsMatch(Convert.ToString(gridCell.Value)))
                {

                    MessageBox.Show($"【{gridCell.OwningColumn.HeaderText}】值设定异常，请重新输入，限定值为【10位以内的整数】", "异常提示！");
                    // 将单元格重置为原始值
                    gridCell.Value = screwList.Where(t => t.Remark == Convert.ToString(row.Cells["Remark"].Value)).First().Capacity;
                    return;
                }
            }
            else if (gridName == "ScrewLength")
            {
                string pattern = @"^\d+(\.\d+)?$";

                // 创建Regex对象并进行匹配测试
                Regex regex = new Regex(pattern);
                if (!regex.IsMatch(Convert.ToString(gridCell.Value)))
                {
                    MessageBox.Show($"【{gridCell.OwningColumn.HeaderText}】值设定异常，请重新输入，限定值为【整数|小数】", "异常提示！");
                    // 将单元格重置为原始值
                    gridCell.Value = screwList.Where(t => t.Remark == Convert.ToString(row.Cells["Remark"].Value)).First().Capacity;
                    return;
                }
            }
        }

        /// <summary>
        /// 螺丝机1发送钉指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtSongDing1_Click(object sender, EventArgs e)
        {
            UnifiedObj.SetLuoSiJiSongDing(true, 1);
            Thread.Sleep(50);
            UnifiedObj.SetLuoSiJiSongDing(false, 1);
        }

        /// <summary>
        /// 螺丝机1发送钉指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtSongDing2_Click(object sender, EventArgs e)
        {
            UnifiedObj.SetLuoSiJiSongDing(true, 2);
            Thread.Sleep(50);
            UnifiedObj.SetLuoSiJiSongDing(false, 2);
        }

        //反转测试
        private void btDianPiFanZhuan_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                DianPiFanZhuan();
            });
        }
        //反转按钮点击状态 012
        int nFanZhuanButtonState = 0;

        private void DianPiFanZhuan()
        {
            if (nFanZhuanButtonState == 0)
            {
                //取消电批急停
                UnifiedObj.DianPiCanWork = true;
                UnifiedObj.SetDianPiCanWork(true);
                Thread.Sleep(50);
                //设置电批任务号
                UnifiedObj.SetDDKTaskNo(1);
                Thread.Sleep(50);

                this.Invoke(new MethodInvoker(() =>
                {
                    btDianPiFanZhuan.Text = "按电批启动键";
                }));

                nFanZhuanButtonState = 1;

                while (nFanZhuanButtonState ==1)
                {
                    if (UnifiedObj.GetStopDown())//按下急停按钮 
                    {
                        UnifiedObj.SetDianPiCanWork(false);
                        return;
                    }
                    //监控启动信号
                    if (UnifiedObj.GetDianPiStart())
                    {
                        UnifiedObj.SetDianPiZhengZhuan(false);
                        this.Invoke(new MethodInvoker(() =>
                        {
                            btDianPiFanZhuan.Text = "点击反转结束";
                        }));
                        nFanZhuanButtonState = 2;
                        break;
                    }
                    Thread.Sleep(50);
                }
            }
            else if (nFanZhuanButtonState == 1)
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    btDianPiFanZhuan.Text = "开始反转";
                }));
                nFanZhuanButtonState = 0;
            }
            else if (nFanZhuanButtonState == 2)
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    btDianPiFanZhuan.Text = "开始反转";
                }));
                //反转结束 电批急停 
                UnifiedObj.SetDianPiStopFanZhuan();
                UnifiedObj.DianPiCanWork = false;
                UnifiedObj.SetDianPiCanWork(false);
                nFanZhuanButtonState = 0;
            }
        }

        /// <summary>
        /// 开锁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btLockOpen_Click(object sender, EventArgs e)
        {
            //开锁
            UnifiedObj.LockOpen(Convert.ToInt16(((Button)sender).Name.Replace("btLockOpen", "")));
        }

        private void label13_Click(object sender, EventArgs e)
        {

        }

        private void label9_Click(object sender, EventArgs e)
        {

        }
    }
}
